import Dep from './Dep';
import Compiler from './Compiler';

export default class ViewModel {
  constructor({ el, data }) {
    this.$el = document.querySelector(el);
    //data()执行拿到对象，并将此对象进行响应式包装。
    this.$data = this.reactive(data());
    this.dep = new Dep();
    this.compiler = new Compiler(this);
  }

  reactive(data) {
    return new Proxy(data, {
      //假如访问 { title: 'xxx' }时，返回属性值target[key]，即obj.title的值
      get: (target, key) => {
        return Reflect.get(target, key);
      },
      set: (target, key, newVal) => {
        //更新数据 如 vm.$data.title = '123';
        const res = Reflect.set(target, key, newVal);
        //更新视图 通知执行所有更新视图相关的函数
        this.dep.notify(key);
        return res;
      }
    });
  }
}
